<?php
header('Content-Type:text/html;charset=utf-8');

// 数据文件
$dataFile = 'guestbook.dat';

// 读取已有留言
$guestbook = file_exists($dataFile) ? unserialize(file_get_contents($dataFile)) : array();

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['name']) && !empty($_POST['message'])) {
    // 过滤和验证输入
    $name = htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8');
    $message = htmlspecialchars(trim($_POST['message']), ENT_QUOTES, 'UTF-8');
    
    // 添加新留言
    $guestbook[] = array(
        'name' => $name,
        'message' => $message,
        'timestamp' => time()
    );
    
    // 保存数据
    file_put_contents($dataFile, serialize($guestbook));
    
    // 重定向防止重复提交
    header('Location: '.$_SERVER['PHP_SELF']);
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>留言板</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        form { max-width: 600px; margin: 0 auto; text-align: left; }
        label { display: inline-block; width: 80px; vertical-align: top; }
        input[type="text"] { width: 300px; }
        textarea { width: 300px; height: 100px; vertical-align: top; }
        input[type="submit"] { margin-left: 85px; padding: 5px 15px; }
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        .no-message { color: #999; text-align: center; margin: 20px 0; }
    </style>
</head>
<body>
    <h2 style="text-align: center;">留言板</h2>
    
    <form method="post" action="">
        <div>
            <label for="name">昵称:</label>
            <input type="text" id="name" name="name" required>
        </div>
        <div>
            <label for="message">留言内容:</label>
            <textarea id="message" name="message" required></textarea>
        </div>
        <div>
            <input type="submit" value="提交留言">
        </div>
    </form>
    
    <h3 style="text-align: center;">留言列表</h3>
    <?php if (!empty($guestbook)): ?>
        <table>
            <tr>
                <th width="15%">昵称</th>
                <th width="60%">留言内容</th>
                <th width="25%">时间</th>
            </tr>
            <?php foreach (array_reverse($guestbook) as $entry): ?>
                <tr>
                    <td><?= $entry['name'] ?></td>
                    <td><?= nl2br($entry['message']) ?></td>
                    <td><?= date('Y-m-d H:i:s', $entry['timestamp']) ?></td>
                </tr>
            <?php endforeach; ?>
        </table>
    <?php else: ?>
        <p class="no-message">暂无留言</p>
    <?php endif; ?>
</body>
</html>